# -*- coding: utf-8 -*-
import io
import sys
import os
import threading
import time
from HttpSocket import HttpSocket

thread_max = 100
thread_inprogress_cnt = 0


class downlaod(threading.Thread):

    udata = {
        '__EVENTTARGET': 'ButtonLogin',
        'TextBoxLogin': '',
        'TextBoxPassword': ''
    }
    urn_pdf_link = ''
    urn_fullpdf_link = ''
    urn_login_link = ''
    urn_Downloadimage_link = ''



    downloadfullpdf = True
    strpath = "$1$2.pdf"
    http = HttpSocket()


    def __init__ (self, urn, outputpath, uid, pwd, downloadfullpdf):
            threading.Thread.__init__(self)
            self.urn = urn
            self.outputpath = outputpath
            self.udata['TextBoxLogin'] = uid
            self.udata['TextBoxPassword'] = pwd
            self.downloadfullpdf = downloadfullpdf

    def login(self):
        self.http.open(self.urn_login_link ,True)
        self.http.open(self.urn_login_link ,True,self.udata)

    def run(self):
        self.login()
        target = self.urn_pdf_link.replace("$1",self.urn)
        if self.downloadfullpdf:
            self.http.open(self.urn_Downloadimage_link.replace("$1",self.urn) ,True)
            target = self.urn_fullpdf_link
        filefullname = self.strpath.replace("$1",self.outputpath).replace("$2",self.urn)
        #print "["+filefullname+"]"
        self.http.download(target,  filefullname, 1)#, 2,51200)
        #http.download(urn_pdf_link.replace("$1",self.urn),  pdf_fullpath+"$1.pdf" )
        global thread_inprogress_cnt
        thread_inprogress_cnt-=1

if __name__ == '__main__':
    print "Downloading.........."

    config_file = sys.argv[1]
    pdf_fullpath = sys.argv[2]

    if not os.path.exists(pdf_fullpath):
        os.mkdir(pdf_fullpath)

    f_urn = io.open(config_file, 'rt', newline='')
    threads = []
    line_idx = 0
    for line in f_urn:
        line_idx +=1

        newline = line.replace("\r\n", "")

        if line_idx == 1:
            uid = newline.split(":")[1]
        elif line_idx == 2:
            pwd = newline.split(":")[1]
        elif line_idx == 3:
            downloadfullpdf = newline.split(":")[1] == '1'
        elif newline:
            # thread.start_new_thread( downlaod, (newline, pdf_fullpath, uid, pwd, downloadfullpdf ) )
            thread = downlaod(newline, pdf_fullpath, uid, pwd, downloadfullpdf )
            threads.append(thread)



    for thread in threads:
        while thread_inprogress_cnt >= thread_max:
            time.sleep(1)
        thread.start()
        thread_inprogress_cnt+=1
        if downloadfullpdf:
            thread.join()
    # for thread in threads:
    #     thread.join()

    # print "Finished.........."






